<template>
  <page-dialog
    :title="dialogInfo.title"
    :width="dialogInfo.width"
    :bt-list="dialogInfo.btList"
    v-model:visible="shows"
  >
    <div class="resources-tree-auth">
      <el-tree
        ref="tree"
        v-model:data="treeInfo.data"
        show-checkbox
        :props="treeInfo.defaultProps"
        :node-key="treeInfo.nodeKey"
        :default-checked-keys="treeInfo.checked"
        @check-change="handleSelectionChange"
        @check="getCurrentNode"
        @node-click="nodeClick"
      />
      <el-tree
        ref="cacheTree"
        :data="cacheTreeInfo.data"
        :props="cacheTreeInfo.defaultProps"
        :node-key="cacheTreeInfo.nodeKey"
        default-expand-all
      />
    </div>
  </page-dialog>
</template>

<script setup name="selectAuth">
import PageDialog from '../PageDialog/index'
import { handleTree } from '@/utils/index'
import {
  roleOrUserGetMenusTreeWithResources,
  getMenusDefaultChecked,
} from '@/api/base.js'
import _ from 'lodash'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  api: {
    type: Function,
    default: roleOrUserGetMenusTreeWithResources,
  },
  showDialog: {
    type: Boolean,
  },
  // 查询已选权限的过滤参数
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  // 查询权限树的过滤参数
  queryTree: {
    type: Object,
    default: function () {
      return {}
    },
  },
})
// 弹窗相关
const dialogInfo = ref({
  title: '选择权限',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    { label: '保存', type: 'primary', event: save, show: true },
  ],
})
// 权限树
const treeInfo = ref({
  data: [],
  nodeKey: 'code',
  checked: [],
  defaultProps: {
    children: 'children',
    label: 'name',
  },
})
const cacheTreeInfo = ref({
  data: [],
  nodeKey: 'code',
  checked: [],
  defaultProps: {
    children: 'children',
    label: 'name',
  },
})
const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})
watch(
  () => treeInfo.value.data,
  (val) => {
    console.log(proxy.$refs.tree.getCheckedNodes(), 'kkkkk')
  }
)
function getCurrentNode(data, data1) {
  //如果是底部节点,寻找父节点,并将父节点的子节点查看按钮设置上
  if (data.children === undefined && data1.halfCheckedNodes != null) {
    data1.halfCheckedNodes.forEach((val) => {
      if (
        val.id === data.parentId &&
        proxy.$refs.tree.getNode(val).indeterminate
      ) {
        val.children.forEach((item) => {
          if (item.code.endsWith(':list')) {
            proxy.$refs.tree.setChecked(item, true, false)
          }
        })
      }
    })
  }
}
function getTree() {
  props.api(props.queryTree).then((resp) => {
    if (resp && resp.success) {
      treeInfo.value.data = resp.data
      getMenusDefaultChecked(props.query).then((res) => {
        if (res && res.success) {
          treeInfo.value.checked = res.data
        }
      })
    }
  })
}
function save() {
  const authList = proxy.$refs.tree.getCheckedNodes(false, true)
  if (!authList || authList.length === 0) {
    proxy.$message({
      message: '控制台权限至少勾选一个',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let itemIndex = authList.findIndex((item) => item.code === 'dashboard')
  if (itemIndex === -1) {
    proxy.$message({
      message: '控制台权限至少勾选一个',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  handleClose()
  emits('callback', authList)
}

const handleSelectionChange = _.debounce(changeData, 2000)
function changeData() {
  setTimeout(() => {
    let checkedNodes = proxy.$fn.deepClone(
      proxy.$refs.tree.getCheckedNodes(false, true)
    )
    checkedNodes.forEach((item, index) => {
      item.children = ''
      if (item.type === 'uri') {
        delete item.id
      }
    })
    cacheTreeInfo.value.data = handleTree(checkedNodes, 'id')
  }, 100)
}

// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}
function nodeClick(obj, node) {
  //点击
  if (!node.childNodes.length) {
    proxy.$refs.tree.setChecked(obj, !node.checked, true)
  }
}
onMounted(() => {
  // hack, 在table创建出来之后再去调用
  proxy.$nextTick(() => {
    getTree()
  })
})
</script>

<style scoped lang="scss">
.resources-tree-auth {
  display: flex;
  justify-content: space-between;
  .el-tree {
    padding: 10px 0;
    height: 300px;
    overflow-y: auto;
    width: 48%;
    border: 1px solid #ecebeb;
  }
}
</style>
